<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { qrcodeApi, categoryApi } from '../api'
import QRCode from 'qrcode'

const router = useRouter()
const route = useRoute()

// 获取路由参数中的二维码ID
const qrcodeId = route.params.id

// 表单数据
const formData = reactive({
  id: '',
  content: '',
  title: '',
  description: '',
  categoryId: ''
})

// 分类列表
const categories = ref([])
// 二维码图片URL
const qrImageUrl = ref('')
// 加载状态
const loading = ref(false)
// 保存状态
const saving = ref(false)
// 错误信息
const errorMsg = ref('')
// 数据加载状态
const dataLoading = ref(false)
// 分类加载状态
const categoriesLoading = ref(false)

// 获取二维码详情
const fetchQRCode = async () => {
  dataLoading.value = true
  errorMsg.value = ''
  
  try {
    const res = await qrcodeApi.getQRCode(qrcodeId)
    const qrcode = res.data
    
    // 填充表单数据
    formData.id = qrcode.id
    formData.content = qrcode.content
    formData.title = qrcode.title
    formData.description = qrcode.description
    formData.categoryId = qrcode.categoryId || ''
    
    // 如果有图片路径，设置图片URL
    if (qrcode.imagePath) {
      qrImageUrl.value = qrcode.imagePath
    } else {
      // 如果没有图片路径但有内容，生成二维码
      if (qrcode.content) {
        await generateQR()
      }
    }
  } catch (error) {
    console.error('获取二维码详情失败:', error)
    errorMsg.value = '获取二维码详情失败: ' + (error.message || '未知错误')
  } finally {
    dataLoading.value = false
  }
}

// 生成二维码
const generateQR = async () => {
  if (!formData.content) {
    errorMsg.value = '请输入二维码内容'
    return
  }
  
  errorMsg.value = ''
  loading.value = true
  
  try {
    // 生成二维码
    const url = await QRCode.toDataURL(formData.content, {
      width: 300,
      margin: 2,
      color: {
        dark: '#000000',
        light: '#ffffff'
      }
    })
    qrImageUrl.value = url
  } catch (error) {
    console.error('生成二维码出错:', error)
    errorMsg.value = '生成二维码失败，请重试'
  } finally {
    loading.value = false
  }
}

// 更新二维码
const updateQRCode = async () => {
  if (!formData.content) {
    errorMsg.value = '请输入二维码内容'
    return
  }
  
  if (!qrImageUrl.value) {
    errorMsg.value = '请先生成二维码'
    return
  }
  
  if (!formData.title) {
    errorMsg.value = '请输入二维码标题'
    return
  }
  
  errorMsg.value = ''
  saving.value = true
  
  try {
    // 更新二维码记录
    await qrcodeApi.updateQRCode({
      id: formData.id,
      content: formData.content,
      title: formData.title,
      description: formData.description,
      categoryId: formData.categoryId || null
    })
    
    // 如果二维码图片是新生成的（以data:开头的Base64数据），则保存图片
    if (qrImageUrl.value.startsWith('data:')) {
      await qrcodeApi.saveQRCodeImage(formData.id, qrImageUrl.value)
    }
    
    // 更新成功，跳转到二维码列表页
    router.push('/dashboard/qrcode')
  } catch (error) {
    console.error('更新二维码出错:', error)
    errorMsg.value = '更新二维码失败: ' + (error.message || '未知错误')
  } finally {
    saving.value = false
  }
}

// 获取分类列表
const fetchCategories = async () => {
  try {
    categoriesLoading.value = true
    const response = await categoryApi.getCategories()
    categories.value = response.data.list || []
  } catch (error) {
    console.error('获取分类列表失败:', error)
    // 如果获取分类失败，不影响主要功能
  } finally {
    categoriesLoading.value = false
  }
}

// 取消编辑
const cancelEdit = () => {
  router.push('/dashboard/qrcode')
}

// 组件挂载时获取二维码详情和分类列表
onMounted(() => {
  fetchQRCode()
  fetchCategories()
})
</script>

<template>
  <div class="qrcode-edit">
    <div class="page-header">
      <h2>编辑二维码</h2>
      <button @click="cancelEdit" class="cancel-btn">取消</button>
    </div>
    
    <!-- 错误提示 -->
    <div v-if="errorMsg" class="error-message">
      {{ errorMsg }}
    </div>
    
    <!-- 数据加载中 -->
    <div v-if="dataLoading" class="loading-container">
      <div class="loading-spinner">
        <div class="spinner"></div>
        <p>加载中...</p>
      </div>
    </div>
    
    <div v-else class="edit-content">
      <!-- 表单区域 -->
      <div class="form-section">
        <form @submit.prevent="generateQR">
          <div class="form-group">
            <label for="content">二维码内容 <span class="required">*</span></label>
            <textarea 
              id="content" 
              v-model="formData.content" 
              placeholder="请输入要生成二维码的内容，如网址、文本等"
              rows="4"
              required
            ></textarea>
          </div>
          
          <div class="form-group">
            <label for="title">标题 <span class="required">*</span></label>
            <input 
              type="text" 
              id="title" 
              v-model="formData.title" 
              placeholder="请输入二维码标题"
              required
            >
          </div>
          
          <div class="form-group">
            <label for="description">描述</label>
            <textarea 
              id="description" 
              v-model="formData.description" 
              placeholder="请输入二维码描述（选填）"
              rows="3"
            ></textarea>
          </div>
          
          <div class="form-group">
            <label for="category">分类</label>
            <select 
              id="category" 
              v-model="formData.categoryId" 
              :disabled="categoriesLoading"
            >
              <option value="">请选择分类（选填）</option>
              <option 
                v-for="category in categories" 
                :key="category.id" 
                :value="category.id"
              >
                {{ category.name }}
              </option>
            </select>
          </div>
          
          <div class="form-actions">
            <button type="submit" :disabled="loading" class="generate-btn">
              {{ loading ? '生成中...' : '重新生成二维码' }}
            </button>
          </div>
        </form>
      </div>
      
      <!-- 预览区域 -->
      <div class="preview-section">
        <h3>二维码预览</h3>
        
        <div class="qr-preview">
          <div v-if="loading" class="loading-spinner">
            <div class="spinner"></div>
            <p>生成中...</p>
          </div>
          <img v-else-if="qrImageUrl" :src="qrImageUrl" alt="生成的二维码" class="qr-image" />
          <div v-else class="empty-preview">
            <p>请输入内容并点击生成按钮</p>
          </div>
        </div>
        
        <button 
          v-if="qrImageUrl" 
          @click="updateQRCode" 
          :disabled="saving" 
          class="save-btn"
        >
          {{ saving ? '保存中...' : '保存修改' }}
        </button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.qrcode-edit {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

h2 {
  margin: 0;
  color: #333;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #666;
  border: 1px solid #ddd;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.cancel-btn:hover {
  background-color: #e0e0e0;
}

.error-message {
  background-color: #ffebee;
  color: #d32f2f;
  padding: 10px;
  border-radius: 4px;
  margin-bottom: 16px;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 300px;
}

.edit-content {
  display: flex;
  gap: 30px;
}

@media (max-width: 768px) {
  .edit-content {
    flex-direction: column;
  }
}

.form-section {
  flex: 1;
}

.preview-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.form-group {
  margin-bottom: 16px;
}

label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

.required {
  color: #f44336;
}

input, textarea, select {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
  transition: border-color 0.3s;
}

input:focus, textarea:focus, select:focus {
  border-color: #4CAF50;
  outline: none;
}

select:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

select option {
  padding: 8px;
  background: white;
  color: #333;
}

.form-actions {
  margin-top: 24px;
}

button {
  padding: 12px;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

button:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

.generate-btn {
  background-color: #4CAF50;
  color: white;
  width: 100%;
}

.generate-btn:hover:not(:disabled) {
  background-color: #45a049;
}

h3 {
  margin-top: 0;
  margin-bottom: 16px;
  color: #333;
  text-align: center;
}

.qr-preview {
  width: 300px;
  height: 300px;
  border: 1px solid #eee;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 20px;
  background-color: #f9f9f9;
}

.qr-image {
  max-width: 100%;
  max-height: 100%;
}

.empty-preview {
  color: #999;
  text-align: center;
}

.loading-spinner {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(0, 0, 0, 0.1);
  border-radius: 50%;
  border-top-color: #4CAF50;
  animation: spin 1s ease-in-out infinite;
  margin-bottom: 10px;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.save-btn {
  background-color: #2196F3;
  color: white;
  width: 200px;
}

.save-btn:hover:not(:disabled) {
  background-color: #1e88e5;
}
</style>